﻿
using SuperSocialShare.Authorize;
using SuperSocialShare.Error;
using SuperSocialShare.Helper;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
namespace SuperSocialShare.Clients
{
    public class SoHuClient : SocialClient
    {
        protected override string AuthorizeUrl
        {
            get { return "https://api.t.sohu.com/oauth2/authorize"; }
        }

        protected override string GetAccessTokenUrl
        {
            get { throw new NotImplementedException(); }
        }

        protected override string GetUserInfoUrl
        {
            get { return "https://api.t.sohu.com/account/verify_credentials.json"; }
        }

        protected override string UpdateStatusUrl
        {
            get { return "https://api.t.sohu.com/statuses/update.json"; }
        }

        protected override string UploadImageUrl
        {
            get { return "https://api.t.sohu.com/statuses/upload.json"; }
        }

        protected override string RevokeAuthorizeUrl
        {
            get { throw new NotImplementedException(); }
        }

        public override SocialType SocialType
        {
            get { return SocialType.SoHu; }
        }

        internal override string GetRequestAuthorizeUrl()
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>() 
            {
                {"client_id",ClientId},
                {"display","mobile"},
                {"response_type","token"},
                {"scope","basic"},
                {"redirect_uri",CallbackUrl}
            };
            return Utility.BuildQueryString(AuthorizeUrl, parameters);
        }

        protected override void GetUserInfoAsync(AuthorizeInfo info)
        {
            HttpWebRequester requester = new HttpWebRequester();
            requester.Authorization = "OAuth2 " + info.AccessToken;
            requester.RequestCompleted += requester_RequestCompleted;
            requester.BeginRequest(GetUserInfoUrl, 0);
        }

        public override void RevokeAuthorizeAysnc()
        {
            throw new NotImplementedException();
        }

        public override void ShareText(string text)
        {
            SoHuAuthorizeInfo authorizeInfo = AuthorizeManager.GetAuthorizeInfo(SocialType) as SoHuAuthorizeInfo;
            if (authorizeInfo != null)
            {
                HttpWebRequester requester = new HttpWebRequester();
                requester.PostContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
                requester.Parameters.Add(new RequestParameter("status", HttpUtility.UrlEncode(text)));
                requester.Authorization = "OAuth2 " + authorizeInfo.AccessToken;
                requester.RequestCompleted += requester_RequestCompleted;
                requester.BeginRequest(UpdateStatusUrl, 1, "POST");
            }
        }

        public override void ShareTextWithImage(string text, byte[] imgdata)
        {
            SoHuAuthorizeInfo authorizeInfo = AuthorizeManager.GetAuthorizeInfo(SocialType) as SoHuAuthorizeInfo;
            if (authorizeInfo != null)
            {
                HttpWebRequester requester = new HttpWebRequester();
                requester.PostContentType = ContentType.MULTIPART_FORM_DATA;
                requester.Parameters.Add(new RequestParameter("status", HttpUtility.UrlEncode(text)));
                requester.Parameters.Add(new RequestParameter("pic", imgdata));
                requester.Authorization = "OAuth2 " + authorizeInfo.AccessToken;
                requester.RequestCompleted += requester_RequestCompleted;
                requester.BeginRequest(UploadImageUrl, 1, "POST");
            }
        }


        /// <summary>
        /// 处理请求授权后的返回数据
        /// </summary>
        /// <param name="data"></param>
        internal override void ProcessResponseDataOfAuthorize(string data)
        {
            SoHuAuthorizeInfo authorizeInfo = new SoHuAuthorizeInfo();
            authorizeInfo.AccessToken = Utility.GetRegexContent(@"(?<=access_token=)[^&]*", data);
            authorizeInfo.Expires = Convert.ToInt32(Utility.GetRegexContent(@"(?<=expires_in=)[^&]*", data));

            AuthorizeManager.Save(authorizeInfo, SocialType);
            GetUserInfoAsync(authorizeInfo);
        }

        void requester_RequestCompleted(RequestCompletedEventArgs e)
        {
            AsyncEventArgs args = new AsyncEventArgs();
            int actionTag = Convert.ToInt32(e.UserData);
            if (e.Error == null)
            {
                SoHuError error = JsonConverter.GetObjectFromJsonString<SoHuError>(e.Result);
                if (error != null && error.ErrorCode != 0)
                {
                    args.Error = error;
                }

                if (actionTag == 0)//请求用户信息后的返回数据 
                {
                    if (args.Error == null)
                    {
                        SoHuAuthorizeInfo authorizeInfo = AuthorizeManager.GetAuthorizeInfo(SocialType) as SoHuAuthorizeInfo;
                        if (authorizeInfo != null)
                        {
                            UserInfo userinfo = new UserInfo();
                            userinfo.Fill(e.Result, SocialType);
                            authorizeInfo.UserInfo = userinfo;
                            args.Result = authorizeInfo;
                        }
                    }
                    OnGetAuthorizeInfoCompleted(args);
                }
                else//分享内容的返回数据
                    OnShareCompleted(args);
            }
            else//WebException
            {
                args.Error = new Error.ErrorBase(e.Error);
                if (actionTag == 0)
                {
                    OnGetAuthorizeInfoCompleted(args);
                }
                else
                {
                    OnShareCompleted(args);
                }
            }
        }
    }
}
